package com.cy.util;

import com.google.common.io.Files;
import lombok.SneakyThrows;
import org.joda.time.DateTime;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.StringJoiner;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author yue.cao
 * @since 12-29-2020
 */
public class U {

	private U() {}

	@SneakyThrows
	public static void sleepRandom() {
		TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(10));
	}

	@SneakyThrows
	public static int sleepRandom(TimeUnit unit, Integer maxMum) {
		int timeout = ThreadLocalRandom.current().nextInt(maxMum);
		unit.sleep(timeout);
		return timeout;
	}

	@SneakyThrows
	public static void sleep(TimeUnit unit, long time) {
		unit.sleep(time);
	}

	@SneakyThrows
	public static void sleep(int time) {
		TimeUnit.SECONDS.sleep(time);
	}

	@SneakyThrows
	public static String readFile(String path) {
		List<String> lines = Files.readLines(new File(path), StandardCharsets.UTF_8);
		return lines.toString();
	}

	@SneakyThrows
	public static List<String> readResourcesFile(String path) {
		return java.nio.file.Files.lines(
				Paths.get(ClassLoader.getSystemResource(path).toURI())
		).collect(Collectors.toList());
	}

	@SneakyThrows
	public static String readResourcesFileOriginal(String path) {
		return java.nio.file.Files.lines(
				Paths.get(ClassLoader.getSystemResource(path).toURI())
		).collect(Collectors.joining(System.lineSeparator()));
	}

	public static void printThreadLog(String msg) {
		System.out.println(new StringJoiner(" | ")
				.add(LocalTime.now().format(DateTimeFormatter.ofPattern("[HH:mm:ss.SSS]")))
				// .add(System.currentTimeMillis() + "")
				.add(String.format("%2d", Thread.currentThread().getId()))
				.add(Thread.currentThread().getName())
				.add(msg).toString());
	}


}
